package net.techmonks.connectivity.shaiya;

/**
 * @author Abhishek Chhajer
 */
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Connecter extends Thread {
    String         serverName;
    String         serverIp;
    int            serverPort;
    int            successCount;
    int            loop;
    FileWriter     fstream = null;
    BufferedWriter br      = null;

    public Connecter(String serverName, String serverIp, int serverPort) {
        this.serverName = serverName;
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        try {
            fstream = new FileWriter("ShaiyaConnectivityOutput.txt", true);
            br = new BufferedWriter(fstream);
        } catch (Exception e) {
            System.out.println("Some Error occured please notify morroc about it on forums, with this message: " + e.getMessage());
        }
    }

    @Override
    public synchronized void run() {
        // System.out.println("Running thread for "+serverName);
        successCount = 0;
        loop = 0;
        for (loop = 0; loop < 1000; loop++) {
            try {
                Socket clientSocket = new Socket(serverIp, serverPort);
                successCount++;
                System.out.print(".");
                clientSocket.close();
            } catch (UnknownHostException e) {
                System.out.println("Some Error occured please notify morroc about it on forums, with this message: " + e.getMessage());
            } catch (IOException e) {
                System.out.println("Some Error occured please notify morroc about it on forums, with this message: " + e.getMessage());
            }
        }
        writeToFile();
    }

    /**
     * TODO File Writing should be synced, currently just writing to the file
     * and
     * hoping that it works.
     */
    private synchronized void writeToFile() {
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
        Date date = new Date();

        try {
            br.write(dateFormat.format(date));
            br.write(" Connection Quality To " + serverName + " is " + (100.0 * successCount) / loop
                    + "%. It should be very close to 100\n");
            br.close();
        } catch (IOException e) {
            System.out.println("Some Error occured please notify morroc about it on forums, with this message: " + e.getMessage());
        }
    }
}
